﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Dao.Basic;
using System.Data;
using System.Windows.Forms;
using CommonLibrary.Common;

namespace ServiceApplication.Service.Basic
{
    public class BasicService
    {
        UserDao userDao = new UserDao();
        StaffDao staffDao = new StaffDao();
        DeptDao deptDao = new DeptDao();
        DutyDao dutyDao = new DutyDao();
        CledDao cledDao = new CledDao();
        MsgDao msgDao = new MsgDao();
        MsgmxDao msgmxDao = new MsgmxDao();
        SrchDao srchDao = new SrchDao();
        SalaDAO salaDao = new SalaDAO();
        FileDao fileDao = new FileDao();
        FolderDao folderDao = new FolderDao();
        ConfigDao configDao = new ConfigDao();
        GzzdDao gzzdDao = new GzzdDao();
        WcdjDao wcdjDao = new WcdjDao();

        #region 用户
        public int AddUser(UserEntity userEntity)
        {
            var user_id = userDao.AddEntity(userEntity);
            var staffEntity = QueryStaff(userEntity.staff_id);
            userDao.AddUserIntoChatTable(userEntity.user_loginid, userEntity.user_psw, userEntity.user_name, staffEntity.staff_email);
            return user_id;
        }

        public void UpdateUser(UserEntity usersEntity)
        {
            userDao.UpdateEntity(usersEntity);
        }

        public void DeleteUser(int id)
        {
            userDao.DleteEntity(id);
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="id">用户编码</param>
        /// <returns>用户类</returns>
        public UserEntity QueryUser(int user_id)
        {
            return userDao.QueryEntity(user_id);
        }

        public UserEntity QueryUser(string user_name)
        {
            return userDao.QueryEntity(user_name);
        }

        /// <summary>
        /// 查询所有可用用户
        /// </summary>
        /// <returns></returns>
        public DataTable QueryAllUsers()
        {
            return userDao.QueryAllUsers();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="usrEnty">username 模糊查询</param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public DataTable QueryUsersByCondition(UserEntity usrEnty, string stime, string etime)
        {
            return userDao.QueryUsersByCondition(usrEnty, stime, etime);
        }

        //
        public DataTable QueryUserBySpqx(int[] spqx_id)
        {
            if (spqx_id == null || spqx_id.Length == 0) return null;
            return userDao.QueryBySpqx(spqx_id);
        }
        //
        public DataTable QueryUserBySpqxDept(int[] spqx_id, int dept_id)
        {
            if (spqx_id == null || spqx_id.Length == 0) return null;
            return userDao.QueryBySpqxDept(spqx_id, dept_id);
        }

        /// <summary>
        /// 查询用户信息
        /// </summary>
        /// <param name="Loginid">账号</param>
        /// <returns>用户类</returns>
        public UserEntity QueryUserByLoginid(string Loginid)
        {
            return userDao.QueryEntityByLoginid(Loginid);
        }

        /// <summary>
        /// 传入数组id，返回dt
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public DataTable QueryUserByIds(String[] ids)
        {
            return userDao.QueryUserByIds(ids);
        }

        public UserEntity QueryUserByUserId(String userid)
        {
            return userDao.QueryEntityByUserId(userid);
        }

        /// <summary>
        ///  查询用户职称
        /// </summary>
        /// <param name="id">用户编号</param>
        /// <returns></returns>
        public String QueryUserById(String id)
        {
            return userDao.QueryUserAuth(id);
        }



        /// <summary>
        /// 登陆名
        /// </summary>
        /// <param name="Loginid">账号</param>
        /// <returns>用户类</returns>
        public bool ExistUser(string Loginid)
        {
            return QueryUserByLoginid(Loginid) != null;
        }

        public void UpdateHeadImg(int id, String imgPath)
        {
            userDao.UpdateHeadImg(id, imgPath);
        }

        public void UpdateLoginTime(String id, String loginTime)
        {
            userDao.UpdateLoginTime(id, loginTime);
        }

        public String QueryUserCount()
        {
            return userDao.QueryUserCount();
        }

        /// <summary>
        ///  用于在treeview上显示部门和人员树节点
        /// </summary>
        /// <returns></returns>
        public TreeNode[] GetUserNodeList()
        {
            DataTable dt_dept = QueryAllDepts();

            NodeHelp nh = new NodeHelp(dt_dept, "部门编码", "部门名称", "上级编码", "上级编码=0");
            TreeNodeCollection tnc = nh.FillNodeList();

            FillLastNodeUser(tnc);
            TreeNode[] tns = new TreeNode[tnc.Count];
            tnc.CopyTo(tns, 0);
            return tns;
        }

        public System.Web.UI.WebControls.TreeNode[] GetWebUserNodeList()
        {
            DataTable dt_dept = QueryAllDepts();
            WebNodeHelp nh = new WebNodeHelp(dt_dept, "部门编码", "部门名称", "上级编码", "上级编码=0");
            System.Web.UI.WebControls.TreeNodeCollection tnc = nh.FillNodeList();

            FillLastWebNodeUser(tnc);
            var tns = new System.Web.UI.WebControls.TreeNode[tnc.Count];
            tnc.CopyTo(tns, 0);
            return tns;
        }



        /// <summary>
        /// 根据部门编码查询用户
        /// </summary>
        /// <param name="dept_id"></param>
        /// <returns></returns>
        public DataTable QueryUserByDeptId(string dept_id)
        {
            return userDao.QueryUserByDeptId(dept_id);
        }

        public DataTable QueryAllAuth()
        {
            return userDao.QueryAllAuth();
        }

        /// <summary>
        ///  更改员工权限
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="authId"></param>
        public void ChangeAuth(String userId, String authId)
        {
            userDao.ChangeAuth(userId, authId);
        }

        public void AddAuth(String authName, String authority)
        {
            userDao.AddAuth(authName, authority);
        }

        /// <summary>
        ///  更改 用户'们'的部门
        /// </summary>
        /// <param name="usrIds"></param>
        /// <param name="deptId"></param>
        public void ChangeDept(String usrIds, String deptId)
        {
            userDao.ChangeDept(usrIds, deptId);
        }

        public Node GetUserNodes()
        {
            Node node = new Node
            {
                Text = "好友列表",
                Value = "0"
            };
            var dt = userDao.QueryAllUsers();
            foreach (DataRow row in dt.Rows)
            {
                node.Nodes.Add(new Node
                {
                    Text = row["用户名称"].ToString(),
                    Value = row["用户编码"].ToString()
                });
            }
            return node;
        }

        public void AddTempUser(String temp_user)
        {
            userDao.AddTempUser(temp_user);
        }

        public DataTable GetTempUsers()
        {
            return userDao.GetTmpUsers();
        }

        public DataTable GetTempUser(String name)
        {
            return userDao.GetTempUser(name);
        }

        #endregion

        #region 员工

        public int AddStaff(StaffEntity staffEntity)
        {
            return staffDao.AddEntity(staffEntity);
        }

        public void DelStaff(int staff_id)
        {
            staffDao.DleteEntity(staff_id);
        }

        public void UpdateStaff(StaffEntity staffEntity)
        {
            staffDao.UpdateEntity(staffEntity);
        }

        public StaffEntity QueryStaff(int staff_id)
        {
            return staffDao.QueryEntity(staff_id);
        }

        public StaffEntity QueryStaff(string staff_name)
        {
            return staffDao.QueryEntity(staff_name);
        }

        public StaffEntity QueryStaffByUserId(int user_id)
        {
            return staffDao.QueryByUserId(user_id);
        }

        public DataTable QueryStaffByLikeName(string staff_name)
        {
            return staffDao.QueryByLikeName(staff_name);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="staff_kybz">在职、停职</param>
        /// <returns></returns>
        public DataTable QueryAllStaff(string staff_kybz)
        {
            return staffDao.QueryAll(staff_kybz);
        }

        public DataTable QueryAllStaff()
        {
            return staffDao.QueryAll(null);
        }

        public DataTable QueryNoUserStaff()
        {
            return staffDao.QueryNoUserAll();
        }

        public DataTable QueryStaffByDeptId(string dept_id)
        {
            return staffDao.QueryByDeptId(dept_id, null);
        }

        public DataTable QueryStaffByDeptId(string dept_id, string staff_kybz)
        {
            return staffDao.QueryByDeptId(dept_id, staff_kybz);
        }


        #endregion

        #region 部门
        public int AddDept(DeptEntity deptEntity)
        {
            return deptDao.AddEntity(deptEntity);
        }

        public void UpdateDept(DeptEntity deptEntity)
        {
            deptDao.UpdateEntity(deptEntity);
        }

        public void DeleteDept(int id)
        {
            deptDao.DleteEntity(id);
        }

        public DeptEntity QueryDept(int id)
        {
            return deptDao.QueryEntity(id);
        }

        public DeptEntity QueryDept(string deptname)
        {
            return deptDao.QueryEntity(deptname);
        }

        public DataTable QueryAllDepts()
        {
            return deptDao.QueryAllDepts();
        }

        public Node GetDeptNodes()
        {
            var dt = deptDao.QueryAllDepts();
            Node rootNode = new Node
            {
                Text = dt.Rows[0]["部门名称"].ToString(),
                Value = dt.Rows[0]["部门编码"].ToString(),
                IsChecked = false,
                ShowCheckBox = true
            };
            var parDt = dt.Select("上级编码=1 and 部门编码 not in (1)");
            foreach (DataRow parRow in parDt)
            {
                var parNode = new Node
                {
                    Text = parRow["部门名称"].ToString(),
                    Value = parRow["部门编码"].ToString(),
                    IsChecked = false,
                    ShowCheckBox = true
                };
                GetChilNodes(dt, parNode, "上级编码=" + parNode.Value);

                rootNode.Nodes.Add(parNode);
            }
            return rootNode;
        }

        public void GetChilNodes(DataTable dt, Node parNode, String filter)
        {
            var chiDt = dt.Select(filter);

            foreach (DataRow chiRow in chiDt)
            {
                var innerNode = new Node
                {
                    Text = chiRow["部门名称"].ToString(),
                    Value = chiRow["部门编码"].ToString(),
                    IsChecked = false,
                    ShowCheckBox = true
                };
                parNode.Nodes.Add(innerNode);
                GetChilNodes(dt, innerNode, "上级编码=" + innerNode.Value);
            }
        }

        #endregion

        #region 职位
        public int AddDuty(DutyEntity dutyEntity)
        {
            return dutyDao.AddEntity(dutyEntity);
        }

        public void UpdateDuty(DutyEntity dutyEntity)
        {
            dutyDao.UpdateEntity(dutyEntity);
        }

        public void DeleteDuty(int duty_id)
        {
            dutyDao.DleteEntity(duty_id);
        }

        public DutyEntity QueryDuty(int duty_id)
        {
            return dutyDao.QueryEntity(duty_id);
        }

        public DutyEntity QueryDuty(string duty_name)
        {
            return dutyDao.QueryEntity(duty_name);
        }

        public DataTable QueryAllDutys()
        {
            return dutyDao.QueryAll();
        }
        #endregion

        #region 网盘 file表

        /// <summary>
        ///  添加文件
        /// </summary>
        /// <param name="fileEntity"></param>
        /// <returns></returns>
        public Int32 StoreAddFile(FileEntity fileEntity)
        {
            return fileDao.AddEntity(fileEntity);
        }

        /// <summary>
        ///  删除文件
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="baseUrl"></param>
        public void StoreDelelteFile(String fileID, String baseUrl)
        {
            fileDao.DeleteFile(fileID, baseUrl);
        }

        /// <summary>
        ///  获得分享文件的用户列表
        /// </summary>
        /// <returns></returns>
        public List<ShareFileModel> StoreGetShareUser(int user_id)
        {
            List<ShareFileModel> shareFileList = new List<ShareFileModel>();
            var userIDs = fileDao.GetShareUserID();
            if (userIDs != null)
            {
                foreach (var id in userIDs)
                {
                    //如果共享文件中存在共享给当前用户的话
                    if (id[1].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(user_id.ToString()))
                    {
                        shareFileList.Add(new ShareFileModel
                        {
                            userID = id[0],
                            userName = userDao.QueryEntity(Int32.Parse(id[0])).user_name,
                            files = new List<FileEntity>()
                        });
                    }
                }
            }
            return shareFileList;
        }

        /// <summary>
        ///  获得用户的分享文件
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<ShareFileModel> StoreGetShareFiles(String userID)
        {
            List<ShareFileModel> shareFileList = new List<ShareFileModel>();
            shareFileList.Add(new ShareFileModel
            {
                files = fileDao.GetShareFileList(userID)
            });
            return shareFileList;
        }

        /// <summary>
        ///  分享文件
        /// </summary>
        /// <param name="fileID"></param>
        public void StoreShareFile(String fileID, String shareToIDs)
        {
            fileDao.ShareFile(fileID, shareToIDs);
        }

        public void StoreShareFileByFolderID(String folderID, String shareToIDs)
        {
            fileDao.ShareFileByFolderID(folderID, shareToIDs);
        }

        /// <summary>
        ///  取消分享
        /// </summary>
        /// <param name="fileID"></param>
        public void StroeUnshareFile(String fileID)
        {
            fileDao.ShareFile(fileID, "");
        }

        /// <summary>
        ///  获得文件详情
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
        public FileEntity StoreGetFile(String fileID)
        {
            return fileDao.QueryEntity(fileID);
        }

        /// <summary>
        ///  获得所有有文件的用户
        /// </summary>
        /// <returns></returns>
        public List<UserFileModel> StoreGetAllFiledUser()
        {
            List<UserFileModel> userFileModel = new List<UserFileModel>();
            var userIDs = fileDao.GetAllFiledUserID();
            if (userIDs != null)
            {
                foreach (var userID in userIDs)
                {
                    userFileModel.Add(new UserFileModel
                    {
                        userID = userID[0],
                        userName = userDao.QueryEntity(Int32.Parse(userID[0])).user_name
                    });
                }
            }
            return userFileModel;
        }



        /// <summary>
        ///  获得用户所有文件
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<UserFileModel> StoreGetAllUserFiles(String userID)
        {
            List<UserFileModel> userFileModel = new List<UserFileModel>();
            var files = fileDao.GetUserFiles(userID);
            userFileModel.Add(new UserFileModel
            {
                files = files
            });
            return userFileModel;
        }

        /// <summary>
        ///  移动文件
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="folderID"></param>
        public void StoreMoveFile(String fileID, String folderID)
        {
            fileDao.MoveFile(fileID, folderID);
        }

        /// <summary>
        ///  重命名
        /// </summary>
        /// <param name="fileID"></param>
        /// <param name="rename"></param>
        public void StoreRenameFile(String fileID, String rename)
        {
            fileDao.RenameFile(fileID, rename);
        }

        public int FileAdd(FileEntity fileEntity)
        {
            return fileDao.AddEntity(fileEntity);
        }

        public void FileDelete(Int32 file_id)
        {
            fileDao.DeleteEntity(file_id);
        }

        public FileEntity FileQuery(int file_id)
        {
            return fileDao.QueryEntity(file_id.ToString());
        }

        public void FileUpdate(FileEntity fileEntity)
        {
            fileDao.UpdateEntity(fileEntity);
        }

        public FileEntity FileQuery(string file_replacename)
        {
            return fileDao.QueryEntity(file_replacename);
        }

        public List<FileEntity> FilesQuery(string file_catalog, String userId)
        {
            return fileDao.QueryEntities(file_catalog, userId);
        }

        public List<FileEntity> FilesQueryByFolderId(String folderId)
        {
            return fileDao.QueryEntities(folderId);
        }


        public List<FileEntity> FilesQuery(String userId)
        {
            return fileDao.QueryEntities(userId);
        }

        public List<FileEntity> FilesQueryShare()
        {
            return fileDao.QueryShareEntities();
        }

        /// <summary>
        /// 获取和所有文件 mlh
        /// </summary>
        /// <returns></returns>
        public DataTable FileQueryAllByUserId(int user_id)
        {
            var dt = fileDao.GetFileByUserId(user_id);
            return dt;
        }

        //模糊查询更具文件名
        public List<FileEntity> FileQuery4Fuzzy(string fileName, string userId)
        {
            var list = fileDao.getFiles4Fuzzy(fileName, userId);
            return list;
        }

        public DataTable FileQueryAllShared()
        {
            var dt = fileDao.GetFileAllShared();
            return dt;
        }

        public DataTable FileQuerySharedByUserId(string user_id)
        {
            var dt = fileDao.GetFileSharedByUserId(user_id);
            return dt;
        }

        //文件共享方法，share_flag:'1,2,5,9'
        public void FileShare(String file_id, String share_flag)
        {
            var file = fileDao.QueryEntity(file_id);
            if (file != null)
            {
                var shareflag_list = file.file_share.Split(',').ToList();
                var shareflag_add_list = share_flag.Split(',').ToList();
                var new_shareflag_list = shareflag_list.Union(shareflag_add_list);
                var new_shareflag_str = string.Join(",", new_shareflag_list.ToArray());
                fileDao.ShareFile(file_id, share_flag);
            }
        }

        public void FileMove(String file_id, String file_catalog)
        {
            fileDao.MoveFile(file_id, file_catalog);
        }



        #endregion

        #region 网盘 fodler表

        /// <summary>
        ///  添加文件夹
        /// </summary>
        /// <param name="folderName"></param>
        /// <param name="createTime"></param>
        /// <param name="userID"></param>
        /// <param name="folderPID"></param>
        /// <returns></returns>
        public Boolean StoreAddFolder(String folderName, String createTime, String userID, String folderPID)
        {
            return folderDao.AddFolder(folderName, createTime, userID, folderPID);
        }

        /// <summary>
        ///  删除文件夹
        /// </summary>
        /// <param name="folderID"></param>
        /// <param name="baseUrl"></param>
        /// <param name="force"></param>
        /// <returns></returns>
        public Boolean StoreDeleteFolder(String folderID, String baseUrl, Boolean force)
        {
            return folderDao.DeleteFolder(folderID, baseUrl, force);
        }

        /// <summary>
        ///  修改文件夹
        /// </summary>
        /// <param name="folderID"></param>
        /// <param name="folderName"></param>
        /// <param name="updateTime"></param>
        /// <param name="folderPID"></param>
        /// <returns></returns>
        public Boolean StoreChangeFolder(String folderID, String folderName, String updateTime, String folderPID, String userID)
        {
            return folderDao.ChangeFolder(folderID, folderName, updateTime, folderPID, userID);
        }

        /// <summary>
        ///  获得文件夹
        /// </summary>
        /// <param name="folderPID"></param>
        /// <returns></returns>
        public FolderList StoreGetFolders(String folderPID, String userID)
        {
            return folderDao.GetFolders(folderPID, userID, FolderType.All);
        }

        public DataTable StoreGetFolders(String folderPID)
        {
            return folderDao.childfolder(folderPID);
        }

        //模糊查询更具文件名
        public List<FolderEntity> FolderQuery4Fuzzy(string folderName, string userId)
        {
            var list = folderDao.getFolders4Fuzzy(folderName, userId);
            return list;
        }

        public DataTable StoreGetFolders8Name(String name)
        {
            return folderDao.childfolder(name);
        }

        public DataTable StoreGetFiles8Name(String name)
        {
            return folderDao.childfolder(name);
        }


        /// <summary>
        /// 根据用户编码获取所有对应文件夹
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public DataTable FolderQueryAllByUserId(int user_id)
        {
            var dt = folderDao.GetFoldersByUserId(user_id);
            return dt;
        }

        //public FolderList StoreGetFoldersWithoutFile(String folderPID, String userID)
        //{
        //    return folderDao.GetFolders(folderPID, userID, FolderType.FolderOnly);
        //}

        /// <summary>
        ///  移动文件夹
        /// </summary>
        /// <param name="folderID"></param>
        /// <param name="folderPID"></param>
        /// <param name="userID"></param>
        /// <returns></returns>
        public Boolean StoreMoveFolder(String folderID, String folderPID, String userID)
        {
            return folderDao.MoveFolder(folderID, folderPID, userID);
        }

        /// <summary>
        ///  文件夹重命名
        /// </summary>
        /// <param name="folderID"></param>
        /// <param name="rename"></param>
        public Boolean StoreRenameFolder(String folderID, String folderPID, String rename, String userID)
        {
            return folderDao.RenameFolder(folderID, folderPID, rename, userID);
        }

        #region 树 For Webstore

        private String foldertemplate = "{{\"id\":\"{0}\", \"name\":\"{1}\", \"pid\":\"{2}\", \"updateTime\":\"{3}\",\" userID\":\"{4}\", \"folders\":{5}, \"files\":{6}}}";
        private String filetemplate = "{{\"name\":\"{0}\", \"filesize\":\"{1}\", \"updateTime\":\"{2}\", \"replacename\":\"{3}\", \"id\":\"{4}\",\"share\":\"{5}\", \"ext\":\"{6}\"}}";
        /// <summary>
        ///  获得文件树json格式
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public String StoreGetStoreJsonString(String userID)
        {
            var folder = storeGetStoreTree(userID, "");
            var result = storeGetStroeJsonString(folder);
            return result;
        }

        public String StoreGetStoreJsonString(String userID, String ignoreCaseFolderPID)
        {
            var folder = storeGetStoreTree(userID, ignoreCaseFolderPID);
            var result = storeGetStroeJsonString(folder);
            return result;

        }

        private String storeGetStroeJsonString(FolderNode folderNode)
        {
            var filestr = String.Empty;
            if (folderNode.Files.Count > 0)
            {
                filestr += "[";
                for (int index = 0; index < folderNode.Files.Count; index++)
                {
                    var file = folderNode.Files[index];
                    filestr += String.Format(filetemplate, file.file_name, file.file_size, file.file_utime, file.file_replacename, file.file_id, file.file_share, file.file_ext);
                    if (index != folderNode.Files.Count - 1)
                        filestr += ",";
                }
                filestr += "]";
            }
            else
                filestr += "\"\"";

            var folderstr = String.Empty;
            if (folderNode.Folders.Count > 0)
            {
                folderstr += "[";
                for (int index = 0; index < folderNode.Folders.Count; index++)
                {
                    var folder = folderNode.Folders[index];
                    folderstr += storeGetStroeJsonString(folder);
                    if (index != folderNode.Folders.Count - 1)
                        folderstr += ",";
                }
                folderstr += "]";
            }
            else
                folderstr += "\"\"";

            var result = String.Format(foldertemplate, folderNode.FolderID, folderNode.FolderName, folderNode.FolderPID, folderNode.UpdateTime, folderNode.UserID, folderstr, filestr);
            return result;
        }

        private FolderNode storeGetStoreTree(String userID, String ignoreCaseFolderPID)
        {
            var dt = folderDao.GetFolderNodes(userID);
            FolderNode folderNode = new FolderNode();

            folderNode.FolderID = "0";
            folderNode.FolderName = "网盘";
            folderNode.FolderPID = "0";
            folderNode.UpdateTime = "2012/9/17";
            folderNode.UserID = userID;
            folderNode.CreateTime = "2012/9/17";

            storeGetStoreTree(dt, folderNode, "0", userID, ignoreCaseFolderPID);
            return folderNode;
        }

        private void storeGetStoreTree(DataTable dt, FolderNode rootNode, String pid, String userID, String ignoreCaseFolderPID)
        {
            if (pid == ignoreCaseFolderPID)
                return;
            var result = dt.Select("folder_pid=" + pid).Cast<DataRow>();
            foreach (DataRow item in result)
            {
                var node = new FolderNode
                {
                    FolderID = item["folder_id"].ToString(),
                    FolderPID = item["folder_pid"].ToString(),
                    FolderName = item["folder_name"].ToString(),
                    CreateTime = item["folder_ctime"].ToString(),
                    UpdateTime = item["folder_utime"].ToString(),
                    UserID = item["user_id"].ToString()
                };
                rootNode.Folders.Add(node);
                storeGetStoreTree(dt, node, node.FolderID, userID, ignoreCaseFolderPID);
            }

            rootNode.Files.AddRange(fileDao.GetFileList(pid, userID));
        }


        #endregion

        #region 树节点 For Mail

        public Node GetStoreTree(String userID)
        {
            var dt = folderDao.GetFolderNodes(userID);
            Node folderNode = new Node();
            folderNode.Text = "我的附件";
            folderNode.Value = "appendix";
            getStoreTree(dt, folderNode, "0", userID);
            return folderNode;
        }

        private void getStoreTree(DataTable dt, Node rootNode, String pid, String userID)
        {
            var result = dt.Select("folder_pid=" + pid).Cast<DataRow>();
            foreach (DataRow item in result)
            {
                var node = new Node
                {
                    Text = item["folder_name"].ToString(),
                    Value = "appendix"
                };
                if (!isEmptyDirectory(dt, item["folder_id"].ToString(), userID))
                    rootNode.Nodes.Add(node);
                getStoreTree(dt, node, item["folder_id"].ToString(), userID);
            }
            rootNode.Nodes.AddRange(getStoreFileNode(pid, userID));
            //return rootNode;
        }

        private Boolean isEmptyDirectory(DataTable dt, String pid, String userID)
        {
            var result = dt.Select("folder_pid=" + pid).Cast<DataRow>();
            var files = getStoreFileNode(pid, userID);
            if (files.Count > 0)
                return false;
            else
            {
                foreach (DataRow item in result)
                {
                    isEmptyDirectory(dt, item["folder_id"].ToString(), userID);
                }
                return true;
            }
        }

        private List<Node> getStoreFileNode(String pid, String userID)
        {
            List<Node> fileNodes = new List<Node>();
            var files = fileDao.GetFileList(pid, userID);
            foreach (var item in files)
            {
                fileNodes.Add(new Node
                {
                    Text = item.file_name,
                    Value = item.file_replacename + item.file_ext
                });
            }
            return fileNodes;
        }

        #endregion

        #endregion

        #region 通讯录
        TxlDao txlDao = new TxlDao();
        TxlGroupDao txlGroupDao = new TxlGroupDao();

        public int AddTxl(TxlEntity txl)
        {
            return txlDao.AddEntity(txl);
        }

        public void DelTxl(int txl_id)
        {
            txlDao.DleteEntity(txl_id);
        }

        public void UpdateTxl(TxlEntity txl)
        {
            txlDao.UpdateEntity(txl);
        }

        public TxlEntity QueryTxl(int txl_id)
        {
            return txlDao.QueryEntity(txl_id);
        }

        public TxlEntity QueryTxl(int user_id, string txl_name)
        {
            return txlDao.QueryEntity(user_id, txl_name);
        }

        /// <summary>
        /// 模糊查询
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="txl_name"></param>
        /// <returns></returns>
        public DataTable QueryTxlForFuzzy(int user_id, string txl_name)
        {
            return txlDao.QueryForFuzzy(user_id, txl_name);
        }

        public DataTable QueryTxlByTxlGroupId(int txlgroup_id)
        {
            return txlDao.QueryEntityByGroupId(txlgroup_id);
        }

        public DataTable QueryTxlByUserId(int user_id)
        {
            return txlDao.QueryByUserId(user_id);
        }

        public DataTable QueryAllTxl()
        {
            return txlDao.QueryAll();
        }


        //txlgroup
        public void AddTxlGroup(TxlGroupEntity txlGroup)
        {
            txlGroupDao.AddEntity(txlGroup);
        }

        public void DelTxlGroup(int txlGroup_id)
        {
            txlGroupDao.DleteEntity(txlGroup_id);
        }

        public void UpdateTxlGroup(TxlGroupEntity txlGroup)
        {
            txlGroupDao.UpdateEntity(txlGroup);
        }

        public TxlGroupEntity QueryTxlGroup(int txlGroup_id)
        {
            return txlGroupDao.QueryEntity(txlGroup_id);
        }

        public TxlGroupEntity QueryTxlGroup(string user_id, string txlGroup_name)
        {
            return txlGroupDao.QueryEntity(user_id, txlGroup_name);
        }



        /// <summary>
        /// 获取用户id对应的所有txl小组
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public DataTable QueryTxlGroupByUserId(int user_id)
        {
            return txlGroupDao.QueryByUserId(user_id);
        }

        public Node GetTxlTree(int user_id, string tree_name)
        {
            Node root = new Node(tree_name, "0", true, false, false, "小组");
            var dt_txlgroup = txlGroupDao.QueryEntityByUserId(user_id);
            for (int i = 0; i < dt_txlgroup.Rows.Count; i++)
            {
                int txlgroup_id = int.Parse(dt_txlgroup.Rows[i]["小组编号"].ToString());
                string txlgroup_name = dt_txlgroup.Rows[i]["名称"].ToString();
                Node group = new Node()
                {
                    Expand = false,
                    ShowCheckBox = false,
                    Text = txlgroup_name,
                    Value = txlgroup_id.ToString(),
                    Tag = "小组"
                };

                var dt_txl = txlDao.QueryEntityByGroupId(txlgroup_id);
                for (int j = 0; j < dt_txl.Rows.Count; j++)
                {
                    string txl_name = dt_txl.Rows[j]["名称"].ToString();
                    int txl_id = int.Parse(dt_txl.Rows[j]["编号"].ToString());
                    group.Nodes.Add(new Node()
                    {
                        Expand = false,
                        ShowCheckBox = false,
                        Text = txl_name,
                        Value = txl_id.ToString(),
                        Tag = "组员",
                    });

                }
                root.Nodes.Add(group);
            }

            return root;

        }


        //公司员工 tree
        public Node GetTxlTreeYhList(string tree_name)
        {
            Node root = new Node(tree_name, "0", false, false, false, "小组");
            var dt_depts = QueryAllDepts();
            var dt_usres = QueryAllUsers();
            dt_usres = dt_usres.Select("状态 = 1 ").CopyToDataTable();
            for (int i = 0; i < dt_depts.Rows.Count; i++)
            {
                int dept_id = int.Parse(dt_depts.Rows[i]["部门编码"].ToString());
                string dept_name = dt_depts.Rows[i]["部门名称"].ToString();
                Node deptNode = new Node()
                {
                    Expand = false,
                    ShowCheckBox = false,
                    Text = dept_name.ToString(),
                    Value = dept_id.ToString(),
                    Tag = "小组"
                };
                var tmp_users = dt_usres.Select("部门编码='" + dept_id.ToString() + "'");
                if (tmp_users.Count() > 0)
                {
                    var dt_tmp_users = tmp_users.CopyToDataTable();
                    for (int j = 0; j < dt_tmp_users.Rows.Count; j++)
                    {
                        int user_id = int.Parse(dt_tmp_users.Rows[j]["用户编码"].ToString());
                        string user_name = dt_tmp_users.Rows[j]["用户名称"].ToString();
                        Node userNode = new Node()
                        {
                            Expand = false,
                            ShowCheckBox = false,
                            Text = user_name.ToString(),
                            Value = user_id.ToString(),
                            Tag = "组员"
                        };
                        deptNode.Nodes.Add(userNode);
                    }
                }
                root.Nodes.Add(deptNode);
            }


            return root;
        }
        #endregion

        #region 日程表

        // 遍历本月记录获得有记录的日期
        public String GetOutstandDate(String year, String month, Int32 dayCout, String userId)
        {
            return cledDao.GetOutstandDates(year, month, dayCout, userId);
        }

        public String[][] GetNotes(String date, String userId)
        {
            return cledDao.GetNotes(date, userId);
        }

        public void DoNote(CledEntity cledEntity, String userId)
        {
            cledDao.AddNote(cledEntity, userId);
        }

        public void UpdateNote(CledEntity cledEntity)
        {
            cledDao.UpdateNote(cledEntity);
        }

        public void DeleteNote(String noteId)
        {
            cledDao.DeleteNote(noteId);
        }

        public DataTable GetNotesUtilCurrDay(String date, String userId)
        {
            return cledDao.GetNotesUtilCurrDay(date, userId);
        }

        public void ReadNote(String noteId)
        {
            cledDao.ReadNote(noteId);
        }
        #endregion

        #region 站内信
        public int AddMsg(MsgEntity msgEntity)
        {
            var msg_id = msgDao.AddEntity(msgEntity);
            var creater_user = QueryStaffByUserId(msgEntity.creater_id);
            if (creater_user == null) return -1;
            //添加msgmx 
            var arr_reveiverids = msgEntity.receiver_ids.Split(','); ;
            foreach (var item in arr_reveiverids)
            {
                if (string.IsNullOrEmpty(item))
                    continue;

                var receiver_user = QueryUser(int.Parse(item));
                if (receiver_user == null) continue;
                var receiver_staff = QueryStaff(receiver_user.staff_id);

                msgmxDao.AddEntity(new MsgmxEntity()
                {
                    msg_id = msg_id,
                    msgmx_isread = 0,
                    receiver_id = int.Parse(item)
                });
                //如果接收人有站内信短信提示的权限，则短信提示
                if (receiver_user.user_znxdx == 1 && !string.IsNullOrEmpty(receiver_staff.staff_mobile))
                {
                    string msgcontent = string.Format("{0}:{1}   ---{2}", msgEntity.msg_titile, msgEntity.msg_content, creater_user.staff_name);
                    SMSHelper.DoSendMsg(receiver_staff.staff_mobile, msgcontent);
                }

            }
            return msg_id;
        }

        public void UpdateMsg(MsgEntity msgEntity)
        {
            msgDao.UpdateEntity(msgEntity);
        }

        public void DeleteMsg(int msg_id)
        {
            msgDao.DleteEntity(msg_id);
        }

        public DataTable QuerySavedMsg(String userId)
        {
            return msgDao.QuerySavedEntity(userId);
        }

        public DataTable QuerySavedMsgByCondition(String userId, String title, String content, String stime, String etime)
        {
            return msgDao.QuerySavedEntityByCondition(userId, title, content, stime, etime);
        }

        public MsgEntity QueryMsg(int msg_id)
        {
            return msgDao.QueryEntity(msg_id);
        }

        public DataTable QueryAllMsg()
        {
            return msgDao.QueryAll();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="createId"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="saveflag"></param>
        /// <param name="readflag">全部已读，部分已读，未读</param>
        /// <returns></returns>
        public DataTable QueryMsgByCodition(Int32 createId, String title, String content, String stime, String etime, Int32 saveflag, String readflag)
        {
            var msgEntity = new MsgEntity
            {
                creater_id = createId,
                msg_content = content,
                msg_titile = title,
                msg_save = saveflag,
                msg_isread = readflag
            };
            var dt = msgDao.QueryMsgByEntity(msgEntity, stime, etime);
            dt.Columns.Add(new DataColumn("接收人"));
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string receiver_ids = dt.Rows[i]["接收人编码组"].ToString();
                    string[] receivers = receiver_ids.Split(new char[] { ',' });
                    var dt_tmp_users = QueryUserByIds(receivers);
                    var arr_receiver_names = new String[0];
                    if (dt_tmp_users != null && dt_tmp_users.Rows.Count > 0)
                        arr_receiver_names = dt_tmp_users.AsEnumerable().Select(x => x.Field<string>("用户名称").ToString()).ToArray();
                    var receiver_names = string.Join(",", arr_receiver_names);
                    dt.Rows[i]["接收人"] = receiver_names;
                }
            }
            return dt;
        }

        public DataTable QueryMsg(int creater_id, int receiver_id, string title, string content, string stime, string etime)
        {
            var dt = msgDao.QueryMsg(creater_id, receiver_id, title, content, stime, etime);
            dt.Columns.Add(new DataColumn("接收人"));
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string receiver_ids = dt.Rows[i]["接收人编码组"].ToString();
                    string[] receivers = receiver_ids.Split(new char[] { ',' });
                    var dt_tmp_users = QueryUserByIds(receivers);
                    var arr_receiver_names = new String[0];
                    if (dt_tmp_users != null && dt_tmp_users.Rows.Count > 0)
                        arr_receiver_names = dt_tmp_users.AsEnumerable().Select(x => x.Field<string>("用户名称").ToString()).ToArray();
                    var receiver_names = string.Join(",", arr_receiver_names);
                    dt.Rows[i]["接收人"] = receiver_names;
                }
            }
            return dt;
        }

        public DataTable QueryReceveMsgByCondition(int receiver_id, String title, String content, String stime, String etime, Int32 savefalg, int? readflag)
        {
            var msgEntity = new MsgEntity
            {
                msg_content = content,
                msg_titile = title,
                msg_save = savefalg
            };
            var dt = msgDao.QueryRecMsgByEntity(msgEntity, receiver_id, stime, etime);
            dt = filterReviceMsg(receiver_id, readflag, dt);
            dt.Columns.Add(new DataColumn("接收人"));
            if (dt != null)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string receiver_ids = dt.Rows[i]["接收人编码组"].ToString();
                    string[] receivers = receiver_ids.Split(new char[] { ',' });
                    var dt_tmp_users = QueryUserByIds(receivers);
                    var arr_receiver_names = dt_tmp_users.AsEnumerable().Select(x => x.Field<string>("用户名称").ToString()).ToArray();
                    var receiver_names = string.Join(",", arr_receiver_names);
                    dt.Rows[i]["接收人"] = receiver_names;
                }
            }
            return dt;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="receiver_id"></param>
        /// <param name="isread">已读标志（1:已读;0:未读）</param>
        /// <returns></returns>
        public DataTable QueryMsgs(int receiver_id, int? readflag)
        {
            DataTable dt = QueryAllMsg();
            dt = filterReviceMsg(receiver_id, readflag, dt);
            return dt;

        }
        public DataTable QueryMsgmx(int msg_id)
        {
            return msgmxDao.QueryByMsgId(msg_id);

        }

        /// <summary>
        /// 从参数dt里根据条件过滤
        /// </summary>
        /// <param name="receiver_id"></param>
        /// <param name="readflag"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DataTable filterReviceMsg(int receiver_id, int? readflag, DataTable dt)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                MsgmxEntity mme = msgmxDao.QueryEntity(int.Parse(dt.Rows[i]["编码"].ToString()), receiver_id);
                string receiver_ids = dt.Rows[i]["接收人编码组"].ToString();
                string[] receivers = receiver_ids.Split(new char[] { ',' });

                if (!receivers.Contains(receiver_id.ToString()) || mme == null)
                {
                    dt.Rows.RemoveAt(i);
                    i--;
                    continue;
                }
                if (null != readflag)
                {
                    if (mme.msgmx_isread != readflag)
                    {
                        dt.Rows.RemoveAt(i);
                        i--;
                        continue;
                    }
                }
            }

            dt.AcceptChanges();
            return dt;
        }

        public DataTable QueryMsgsByCreaterId(int creater_id)
        {
            DataTable dt = QueryAllMsg();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string tmp = dt.Rows[i]["发起人编码"].ToString();

                if (tmp != creater_id.ToString())
                {
                    dt.Rows.RemoveAt(i);
                    i--;
                    continue;
                }
            }
            dt.AcceptChanges();
            return dt;
        }

        /// <summary>
        /// 传入id将该消息更新为已读
        /// </summary>
        /// <param name="msg_id"></param>
        public void DoMsgRead(int msg_id, int receiver_id)
        {
            //已读标志使用msgmx表里的已读标志
            msgmxDao.UpdateReadFlag(msg_id, receiver_id, 1);
            var dt = msgmxDao.QueryByMsgId(msg_id);

            //更新msg_isread 标志
            MsgEntity msgEntity = msgDao.QueryEntity(msg_id);
            int num = dt.Select("已读标志 = 0").Count();
            if (dt.Select("已读标志 = 0").Count() == 0)
            {
                msgEntity.msg_isread = "全部已读";
                msgDao.UpdateEntity(msgEntity);
            }
            else
            {
                msgEntity.msg_isread = "部分已读";
                msgDao.UpdateEntity(msgEntity);
            }

            if (dt.Select("已读标志 = 1").Count() == 0)
            {
                msgEntity.msg_isread = "未读";
                msgDao.UpdateEntity(msgEntity);
            }
        }

        #endregion

        #region 菜单

        /// <summary>
        ///  返回菜单列表字典型
        /// </summary>
        /// <returns></returns>
        public DataTable MenuQueryAll()
        {
            return userDao.QueryMenuList();
        }

        public Node[] GetMenuNodeList()
        {
            var dt = userDao.QueryMenuList();
            var list_rootmenu = dt.Select("menu_supid = '0' ").ToList();
            List<Node> parMenus = new List<Node>();
            for (int i = 0; i < list_rootmenu.Count; i++)
            {
                var parNode = new Node
                {
                    Value = list_rootmenu[i]["menu_id"].ToString(),
                    Text = list_rootmenu[i]["menu_name"].ToString(),
                    ShowCheckBox = true,
                    Tag = list_rootmenu[i]["menu_supid"].ToString()
                };

                var list_childmenu = dt.Select("menu_supid ='" + list_rootmenu[i]["menu_id"].ToString() + "'").ToList();
                foreach (var item in list_childmenu)
                {
                    parNode.Nodes.Add(new Node
                    {
                        Value = item["menu_id"].ToString(),
                        Text = item["menu_name"].ToString(),
                        ShowCheckBox = true,
                        Tag = item["menu_supid"].ToString()
                    });
                }
                parMenus.Add(parNode);
            }

            //Int32 prevIndex = 0;
            //Int32 currIndex = 0;
            //List<Node> chilMenus = new List<Node>();
            //foreach (System.Data.DataRow row in dt.Rows)
            //{
            //    if (row["menu_supid"].ToString() == "0")
            //        parMenus.Add(new Node
            //        {
            //            Value = row["menu_id"].ToString(),
            //            Text = row["menu_name"].ToString()
            //        });
            //    else
            //    {
            //        currIndex = Convert.ToInt32(row["menu_supid"]);
            //        if (currIndex > prevIndex)
            //        {
            //            parMenus[prevIndex].Nodes = chilMenus;
            //            chilMenus = new List<Node>();
            //            chilMenus.Add(new Node
            //            {
            //                Value = row["menu_id"].ToString(),
            //                Text = row["menu_name"].ToString()
            //            });
            //            prevIndex = currIndex;
            //        }
            //        else
            //            chilMenus.Add(new Node
            //            {
            //                Value = row["menu_id"].ToString(),
            //                Text = row["menu_name"].ToString()
            //            });
            //    }
            //}

            //parMenus[currIndex].Nodes = chilMenus;
            return parMenus.ToArray();
        }

        public Node[] GetPersMenuNodes(String authId)
        {
            var nodes = GetMenuNodeList();
            var authority = userDao.GetAutority(authId);
            var parMenus = authority.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);// CommonMethod.splitString(authority, ';');

            List<Node> parNodes = new List<Node>();

            //List<Node> chiNodes;
            foreach (var parMenu in parMenus)
            {
                var chiMenus = CommonMethod.splitString(parMenu, ',');
                var menu_id = Convert.ToInt32(chiMenus[0]);

                var parNode = nodes.SingleOrDefault(x => x.Value == menu_id.ToString());
                if (parNode == null) continue;
                parNode.IsChecked = true;

                //直接跳过第一个节点
                for (int chiIndex = 1; chiIndex < chiMenus.Length; chiIndex++)
                {
                    var childNode = parNode.Nodes.SingleOrDefault(x => x.Value == chiMenus[chiIndex]);
                    if (childNode != null) childNode.IsChecked = true;
                }

                //chiNodes = new List<Node>();
                //for (int chiIndex = 1; chiIndex < chiMenus.Length; chiIndex++)
                //{
                //    chiNodes.Add(parNode.Nodes[Convert.ToInt32(chiMenus[chiIndex]) - 1]);
                //}
                //parNodes.Add(new Node
                //{
                //    Text = parNode.Text,
                //    Value = parNode.Value,
                //    Nodes = chiNodes
                //});
            }

            return nodes;
        }

        #endregion

        #region 全局搜索

        public DataTable QuerySendMsgForSearch(String userId, String searchText)
        {
            return srchDao.QuerySendMsgForSearch(userId, searchText);
        }

        public DataTable QueryReceiveMsgForSearch(String userId, String searchText)
        {
            return srchDao.QueryReceiveMsgForSearch(userId, searchText);
        }

        public DataTable QueryFormListForSearch(String userId, String searchText)
        {
            return srchDao.QueryFormListForSearch(userId, searchText);
        }

        public DataTable QueryNotifyForSearch(String userId, String searchText)
        {
            return srchDao.QueryNotifyForSearch(userId, searchText);
        }

        public DataTable QueryWfTemplateForSearch(String userId, String searchText)
        {
            return srchDao.QueryWfTemplateForSearch(userId, searchText);
        }

        public DataTable QueryWfInsForSearch(String userId, String searchText)
        {
            return srchDao.QueryWfInsForSearch(userId, searchText);
        }
        public DataTable QueryWfTaskForSearch(String userId, String searchText)
        {
            return srchDao.QueryWfTaskForSearch(userId, searchText);
        }

        #endregion

        #region 邮件

        /// <summary>
        ///  获得邮箱树节点
        /// </summary>
        /// <returns></returns>
        public Node GetMailNodes()
        {
            var deptNodes = GetDeptNodes();
            var dt = staffDao.QueryAll(null);
            dt = dt.Select("在职标志 ='在职' ").CopyToDataTable();
            //return null;
            foreach (var Node in deptNodes.Nodes)
            {
                var filter = "部门编码 = " + Node.Value;
                FillMailNode(dt, Node, filter);
            }
            return deptNodes;
        }

        public void FillMailNode(DataTable dt, Node parNode, String filter)
        {
            var userdt = dt.Select(filter);
            var rowCount = userdt.Count();
            var parNodeCount = parNode.Nodes.Count;
            for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                parNode.Nodes.Add(new Node
                {
                    Text = userdt[rowIndex]["员工名称"].ToString(),
                    Value = userdt[rowIndex]["邮箱"].ToString(),
                    IsChecked = false,
                    ShowCheckBox = true
                });
                if (parNodeCount > 0)
                {
                    for (int nodeIndex = 0; nodeIndex < parNodeCount; nodeIndex++)
                    {
                        var node = parNode.Nodes[nodeIndex];
                        filter = "部门编码 = " + node.Value;
                        FillMailNode(dt, node, filter);
                    }
                }
            }
        }

        public void AddEmail(EmailEntity emailEnty)
        {
            msgDao.AddEmail(emailEnty);
        }

        public DataTable QueryEmails(String userId)
        {
            return msgDao.QueryEmails(userId);
        }

        public EmailEntity QueryEmail(String emailID)
        {
            return msgDao.QueryEmail(emailID);
        }

        public void UpdateEmail(EmailEntity emailEnty)
        {
            msgDao.UpdateMail(emailEnty);
        }

        public void SendedEmail(String emailId)
        {
            msgDao.SendedEmail(emailId);
        }

        #endregion

        #region 其他方法
        void FillLastNodeUser(TreeNodeCollection tnc)
        {
            foreach (TreeNode fnode in tnc)
            {
                if (fnode.Nodes.Count != 0)
                {
                    FillLastNodeUser(fnode.Nodes);
                    return;
                }

                NodeTag nt = fnode.Tag as NodeTag;
                string dupt_id = nt.Value;
                DataTable dt_user = QueryUserByDeptId(dupt_id);
                TreeNode ctn;
                foreach (DataRow dr in dt_user.Rows)
                {
                    ctn = new TreeNode(dr["用户名称"].ToString());
                    NodeTag nh = new NodeTag
                          {
                              Text = ctn.Text,
                              Value = dr["用户编码"].ToString(),
                              bz = string.Empty,
                              level = 1,
                          };
                    ctn.Tag = nh;
                    fnode.Nodes.Add(ctn);
                }
                //设置为次叶节点
                nt.level = 2;
                fnode.Tag = nt;
            }
        }

        void FillLastWebNodeUser(System.Web.UI.WebControls.TreeNodeCollection tnc)
        {
            foreach (System.Web.UI.WebControls.TreeNode node in tnc)
            {
                if (node.ChildNodes.Count != 0)
                {
                    FillLastWebNodeUser(node.ChildNodes);
                    return;
                }

                string dupt_id = node.Value;
                DataTable dt_user = QueryUserByDeptId(dupt_id);
                var tmp = dt_user.Select("在职标志 = '在职' ");
                if (tmp.Count() == 0)
                    return;
                dt_user = tmp.CopyToDataTable();

                System.Web.UI.WebControls.TreeNode tn;
                foreach (DataRow dr in dt_user.Rows)
                {
                    tn = new System.Web.UI.WebControls.TreeNode(dr["用户名称"].ToString());
                    tn.Value = dr["用户编码"].ToString();

                    tn.ShowCheckBox = true;
                    node.ChildNodes.Add(tn);
                }
            }
        }

        #endregion

        #region 工资提成

        public DataTable UsersInfoForSalary()
        {
            return salaDao.QueryUsersInfo();
        }

        public DataTable QuerySalaryInfo()
        {
            return salaDao.QuerySalaryInfo();
        }

        public void UpdateSalary(SalaEntity salaEntity)
        {
            salaDao.UpdataOrInsertSalary(salaEntity);
        }

        public String QueryPostName()
        {
            var dt = salaDao.QueryPostName();
            var result = String.Empty;
            var count = dt.Rows.Count;
            if (count == 0) return result;
            for (int index = 0; index < count - 1; index++)
            {
                result += "<option>" + dt.Rows[index]["岗位名称"] + "</option>";
            }
            result += "<option>" + dt.Rows[count - 1]["岗位名称"] + "</option>";
            return result;
        }

        public String QueryRankName()
        {
            var dt = salaDao.QueryRankName();
            var result = String.Empty;
            var count = dt.Rows.Count;
            if (count == 0) return result;
            for (int index = 0; index < count - 1; index++)
            {
                result += "<option>" + dt.Rows[index]["级别名称"] + "</option>";
            }

            result += "<option>" + dt.Rows[count - 1]["级别名称"] + "</option>";
            return result;

        }

        public Boolean AddPost(String postName)
        {
            return salaDao.AddPost(postName);
        }

        public Boolean AddRank(String rankName)
        {
            return salaDao.AddRank(rankName);
        }
        #endregion

        #region 全局配置

        public Boolean AddKey(String key, String value)
        {
            return configDao.AddKey(key, value);
        }

        public void UpdateValue(String key, String value)
        {
            configDao.ChangeValue(key, value);
        }

        public Dictionary<String, String> GetConfigs()
        {
            return configDao.GetConfigs();
        }

        public String GetConfig(String key)
        {
            return configDao.GetConfig(key);
        }
        #endregion

        #region 规则制定

        /// <summary>
        /// 增加新的规则(修改也是)
        /// </summary>
        /// <param name="gzzdEntity"></param>
        /// <returns></returns>
        public int AddNewRules(GzzdEntity gzzdEntity)
        {
            return gzzdDao.AddEntity(gzzdEntity);
        }

        /// <summary>
        /// 查询最新的记录
        /// </summary>
        /// <returns></returns>
        public GzzdEntity QueryDetail()
        {
            return gzzdDao.QueryEntity();
        }

        #endregion

        #region 外出登记

        /// <summary>
        /// 增加新的登记
        /// </summary>
        /// <param name="wcdjEntity"></param>
        /// <returns></returns>
        public int AddNewRegister(WcdjEntity wcdjEntity)
        {
            return wcdjDao.AddEntity(wcdjEntity);
        }

        /// <summary>
        /// 修改条目回来时间
        /// </summary>
        /// <param name="updateId"></param>
        /// <param name="value"></param>
        public void UpdateEtime(string updateId, string value)
        {
            wcdjDao.UpdateEtime(updateId, value);
        }

        /// <summary>
        /// 这个是精确查询,精确到天
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public WcdjEntity QueryEntityByIdAndDate(int userId, string date)
        {
            return wcdjDao.QueryEntityByIdAndDate(userId, date);
        }

        public WcdjEntity WcdjQueryEntity(int wcdj_id)
        {
            return wcdjDao.QueryEntity(wcdj_id);
        }

        /// <summary>
        /// 通过Id查询这个人的全部条目
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataTable QueryWcdjById(int user_id)
        {
            return wcdjDao.QueryWcdjById(user_id);
        }
        public DataTable QueryWcdjAll()
        {
            return wcdjDao.QueryWcdjAll();
        }

        public DataTable QueryWcdjById(int user_id, bool isreturn)
        {
            return wcdjDao.QueryWcdjById(user_id, isreturn);
        }
        /// <summary>
        /// 这个是时间段区间查
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public DataTable QueryEntityByIdAndDateRegion(string userId, string startDate, string endDate)
        {
            return wcdjDao.QueryEntityByIdAndDate(userId, startDate, endDate);
        }

        /// <summary>
        /// 查最近前十的外出地点
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public DataTable QueryStaffTopTenAddr(int userId)
        {
            return wcdjDao.QueryStaffTopTenAddr(userId);
        }

        /// <summary>
        /// 根据ID删人
        /// </summary>
        /// <param name="id"></param>
        public void DelectById(string id)
        {
            wcdjDao.DelectById(id);
        }


        /// <summary>
        /// 不填查询人进行日期查询
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public DataTable QueryEntityByDate(string stime, string etime)
        {
            return wcdjDao.QueryEntityByDate(stime, etime);
        }

        /// <summary>
        /// 更新管理信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="message"></param>
        /// <param name="time"></param>
        public void UpdateManagerById(string id, string message, string time)
        {
            int intid = Convert.ToInt32(id);
            wcdjDao.UpdateManagerById(intid, message, time);
        }

        /// <summary>
        /// 这个是有选中那个仅查询的方法查询人的ID有给值
        /// </summary>
        /// <param name="id"></param>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public DataTable QueryEntityByIdAndDateChecked(string id, string startDate, string endDate)
        {
            return wcdjDao.QueryEntityByIdAndDateChecked(id, startDate, endDate);
        }

        /// <summary>
        /// 这个也是选中那个仅查询方法的ID不给值
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public DataTable QueryEntityByDateChecked(string startDate, string endDate)
        {
            return wcdjDao.QueryEntityByDateChecked(startDate, endDate);
        }

        #endregion

        #region 权限

        public string AuthQueryAutority(string authId)
        {
            if (string.IsNullOrEmpty(authId)) return string.Empty;

            var res = userDao.GetAutority(authId);
            return res;
        }

        public void AuthChange(string authId, string authority)
        {
            userDao.AuthUpdate(authId, authority);
        }
        #endregion
    }
}
